package com.freely.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.freely.R;
import com.freely.R2;
import com.freely.component.activity.NavigationActivity;
import com.freely.data.entities.Group;
import com.freely.data.managerUtils.FreelySharedPreferences;
import com.freely.data.network.ServerException;
import com.freely.data.network.responseEntities.RSGroupInfomation;
import com.freely.ui.adapter.recyclerView.SingleViewAdapter;
import com.freely.ui.viewModel.GroupChatInfomationViewModel;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import okio.ByteString;

public class GroupChatInformationActivity extends NavigationActivity {
    private static final String TAG = "GroupChatInformationAct";
    private GroupChatInfomationViewModel groupChatInfomationViewModel;

    @BindView(R2.id.group_name)
    TextView group_name;
    @BindView(R2.id.group_admin)
    TextView group_admin;
    @BindView(R2.id.group_public)
    TextView group_public_title;
    @BindView(R.id.invitation)
    TextView group_invitation;
    @BindView(R2.id.group_member_edit)
    TextView group_member_edit;
    @BindView(R2.id.action_button)
    AppCompatButton actionButton;
    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R2.id.group_account)
    TextView group_account;
    private long groupId;

    private SingleViewAdapter<RSGroupInfomation.UsersBean> adapter;
    //是否是从群搜索处打开的
    private boolean isSearch = false;

    private static final String exitGroup = "退出群聊";
    private static final String joinGroup = "加入群聊";
    private static final String deleteGroup = "解散群聊";


    private Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: ");
        setContentView(R.layout.activity_group_chat_information);
        groupId = getIntent().getLongExtra(Group.group_id, -1);
        isSearch= getIntent().getBooleanExtra("search",false);
        initInfomation();
    }

    public static void startActivity(@NonNull Context context) {
        Log.d(TAG, "startActivity: tsp");
        Intent intent = new Intent(context, GroupChatInformationActivity.class);
        context.startActivity(intent);
    }

    public void initInfomation() {
        List<RSGroupInfomation.UsersBean> usersBean;
        Log.e(TAG, "initInfomation: "+groupId );

        groupChatInfomationViewModel = ViewModelProviders.of(this).get(GroupChatInfomationViewModel.class);
        groupChatInfomationViewModel.getGroupInfo(groupId);

        //加载群信息
        groupChatInfomationViewModel.getGroup().observe(this, group -> {
            //将数据加载在页面上
            if(group!=null){
                group_name.setText(group.getGroup_name());
                group_admin.setText(group.getGroup_admin().getUser_name());
                group_public_title.setText(group.getGroup_notice());
                toolbar.getMenu().findItem(R.id.edit).setVisible(false);

                if (group.getGroup_admin().getUser_id() != FreelySharedPreferences.getInstance().getUserId()) {
                    group_member_edit.setVisibility(View.GONE);
                    if (isSearch){
                        actionButton.setText(R.string.join_group);
                        group_member_edit.setVisibility(View.GONE);
                        group_invitation.setVisibility(View.GONE);
                    }
                } else {
                    actionButton.setText(R.string.group_delete);
                    toolbar.getMenu().findItem(R.id.edit).setVisible(true);
                }

                group_account.setText(group.getGroup_account());
                adapter.setDataList(group.getUsers());
                adapter.notifyDataSetChanged();
            }

        });
        LinearLayoutManager ms = new LinearLayoutManager(this);
        ms.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(ms);
        adapter = new SingleViewAdapter<>(
                null,
                R.layout.activity_group_chat_information_recycler_item
        ).onBindView((holder, position) -> {
            ImageView headIcon = holder.getView(R.id.imageView1);

            RSGroupInfomation.UsersBean usersBean1 = groupChatInfomationViewModel.getGroup().getValue().getUsers().get(position);
            Glide.with(this)
                    .load(ByteString.decodeBase64(usersBean1.getUser_image()).toByteArray())
                    .apply(RequestOptions.circleCropTransform())
                    .into(headIcon);

            if (!holder.itemView.hasOnClickListeners()) {
                holder.itemView.setOnClickListener(GroupChatInformationActivity.this::RVItemOnClick);
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void RVItemOnClick(View view) {
        Log.e(TAG, "RVItemOnClick:" + "乱点头像");
    }

    @OnClick(R.id.action_button)
    void click() {
        String string = actionButton.getText().toString();
        switch (string) {
            case joinGroup:
                Log.e(TAG, "click: 加入群聊");
                applyGroup();
                finish();
                break;

            case deleteGroup:
                Log.e(TAG, "click: 解散群聊");
                groupChatInfomationViewModel.deleteGroup(groupId);
                groupChatInfomationViewModel.getIsDone().observe(this,ss->{
                    Log.e(TAG, "observe: " +"aaaa");
                    this.finish();
                    if(GroupChatInfomationViewModel.IS_DONE.equals(ss)){
                        Log.e(TAG, "observe: " );
                        HomeActivity.startActivity(this,HomeActivity.GROUP_REMOVE,groupId);
                    }
                });
                break;
            case exitGroup:
                Log.e(TAG, "click: 退出群聊");
                groupChatInfomationViewModel.exitGroup(groupId);
                this.finish();
                groupChatInfomationViewModel.getIsDone().observe(this,ss->{
                    if(GroupChatInfomationViewModel.IS_DONE.equals(ss))
                        HomeActivity.startActivity(this,HomeActivity.GROUP_REMOVE,groupId);
                });
                break;
        }
    }
    public static void startActivity(Context context,long groupId,boolean isSearch){
        Intent intent = new Intent(context, GroupChatInformationActivity.class);
        Log.d(TAG, "startActivity: "+groupId);
        intent.putExtra(Group.group_id, groupId);
        intent.putExtra("search", isSearch);
        context.startActivity(intent);
    }

    @OnClick(R.id.group_member_edit)
     void dddd(){
        Log.e(TAG, "dddd: "+"编辑" );
        GroupChatDeleteMemberActivity.startActivity(this,groupId);
    }

    @Override
    public void onResume() {
        super.onResume();
        initInfomation();
    }

    @Override
    protected void onCreateToolbar(Toolbar toolbar, TextView title, ImageButton logo) {
        super.onCreateToolbar(toolbar, title, logo);

        this.toolbar =toolbar;
        this.toolbar.inflateMenu(R.menu.detail);
        this.toolbar.setOnMenuItemClickListener(item -> {
            GroupInformationEditActivity.startActivity(this, groupId);
            return false;
        });
    }

    @OnClick(R2.id.invitation)
    void invitationListener() {
        InviteGroupMemberActivity.Companion.startActivity(
                this,
                FreelySharedPreferences.getInstance().getUserId(),
                groupId
        );
    }


    public void applyGroup(){
        groupChatInfomationViewModel.applyForGroup(groupId);
        groupChatInfomationViewModel.getAppylResult().observe(this, single -> single.subscribe(aBoolean -> {
            //注册成功
            Toast.makeText(
                    GroupChatInformationActivity.this,
                    "申请成功！",
                    Toast.LENGTH_SHORT
            ).show();
            finish();
        }, throwable -> {
            //注册失败
            Log.d(TAG, "accept: "+throwable.getMessage());
            if (throwable instanceof ServerException) {
                Toast.makeText(
                        GroupChatInformationActivity.this,
                        throwable.getMessage(),
                        Toast.LENGTH_SHORT
                ).show();
            }
        }).dispose());
    }
}
